Chapter 16
16-3
// Program to copy one file to another
#include <stdio.h>
/* convert lowercase to uppercase character */
#define TO_UPPER(c) ((c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c)
int main (void)
{
char inName[64], outName[64];
FILE *in, *out;
int c;
printf ("Enter name of file to be copied: ");
scanf ("%63s", inName);
printf ("Enter name of output file: ");
scanf ("%63s", outName);
if ( (in = (FILE *) fopen (inName, "r")) == NULL ) {
fprintf (stderr, "Can't open %s for reading.\n", inName);
return 1;
}
else if ( (out = fopen (outName, "w")) == NULL ) {
fprintf (stderr, "Can't open %s for writing.\n", outName);
return 2;
}
while ( (c = getc (in)) != EOF )
putc (TO_UPPER (c), out);
printf ("File has been copied.\n");
return 0;
}
16-5
/* Program to extract columns from each line of a file
(similar to the UNIX cut command) */
#include <stdio.h>
int main (void)
{
char inName[64];
FILE *in;
int m, n, curcol, c;
printf ("Enter name of file: ");
scanf ("%63s", inName);
printf ("Enter starting and ending column numbers: ");
scanf ("%i%i", &m, &n);
if ( (in = fopen (inName, "r")) == NULL ) {
fprintf (stderr, "Can't open %s for reading.\n", inName);
return 1;
}
else {
curcol = 1;
while ( (c = getc (in)) != EOF ) {
if ( c == '\n' ) {
putchar ('\n');
curcol = 0;
}
else if ( curcol >= m && curcol <= n )
putchar (c);
++curcol;
}
}
}